package com.wenhua.junshao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenhua.junshao.common.CustomerException;
import com.wenhua.junshao.dot.SetmealDto;
import com.wenhua.junshao.entity.Setmeal;
import com.wenhua.junshao.entity.SetmealDish;
import com.wenhua.junshao.mapper.SetmealMapper;
import com.wenhua.junshao.service.SetmealDsihService;
import com.wenhua.junshao.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    SetmealDsihService setmealDsihService;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);
        List<SetmealDish> SetmealDishList = setmealDto.getSetmealDishes();
        //补全套餐菜品关系
        for (SetmealDish setmealDish : SetmealDishList) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDsihService.saveBatch(SetmealDishList);
    }


    //依据ids,批量删除信息
    @Override
    @Transactional
    public void removeWithDish(Long[] ids) {
        //select count(*) from setmeal where id in (1,2,3) and status = 1
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(Setmeal::getId, ids);
        queryWrapper1.eq(Setmeal::getStatus, 1);
        int count = this.count(queryWrapper1);
        if (count > 0) {
            //不能删除
            throw new CustomerException("套餐正在售卖,不可以删除");
        }

        //可以删除
        //参数是数组类型,需转换
        this.removeByIds(Arrays.asList(ids));

        //delete from setmeal_dish where setmeal_id in (1,2,3)
        //删除关系表中的数据----setmeal_dish
        LambdaQueryWrapper<SetmealDish> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.in(SetmealDish::getSetmealId, Arrays.asList(ids));
        setmealDsihService.remove(queryWrapper2);


    }
}
